//
//  GYXUserAccount.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/3.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit

private let accountFile : NSString = "useraccount.json"
class GYXUserAccount: NSObject {
    var access_token: String? //= "2.00HNQp6BeAFyLDaf67d87d1a0vWS8U"
    var uid: String?
    var expires_in: TimeInterval = 0.0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    // 自定义过期日期
    var expiresDate: Date?
    
    // 用户昵称
    var screen_name: String?
    
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    
    /// 重载构造方法
    override init() {
        super.init()
        guard let path = accountFile.cz_appendDocumentDir(),
            // 1,从磁盘中读取数据
            let data = NSData(contentsOfFile: path) as? Data,
            // 2,反序列化 data -> dict
            let dict = (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]) ?? [:]
        else {
            return
        }
        
        // 3,字典转模型
        yy_modelSet(with: dict)
        
        // 比较日期是否过期
        if expiresDate?.compare(Date()) == .orderedAscending {
            print("expiresDate令牌过期")
            access_token = nil
            uid = nil
            try? FileManager.default.removeItem(atPath: path)
        }

    }
    
    
    /// 保存模型
    func saveAccount() {
        // 1. 模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String : AnyObject]) ?? [:]
        dict.removeValue(forKey: "expires_in")
        // 2. 字典序列化data格式
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filepath = accountFile.cz_appendDocumentDir()
        else {
            return
        }
        // 3. 写入磁盘
        (data as NSData).write(toFile: filepath, atomically: true)
       
        print("\(filepath)")
       
    }
   
}
